class LyricLine {
  final Duration time;
  final String text;

  const LyricLine({
    required this.time,
    required this.text,
  });
}

class LyricParser {
  static List<LyricLine> parse(String? lrcContent) {
    if (lrcContent == null || lrcContent.isEmpty) {
      return [];
    }

    final List<LyricLine> lyrics = [];
    final lines = lrcContent.split('\n');

    for (String line in lines) {
      line = line.trim();
      if (line.isEmpty) continue;

      // 匹配时间标签格式 [mm:ss.xx] 或 [mm:ss]
      final RegExp timeRegex = RegExp(r'\[(\d{2}):(\d{2})(?:\.(\d{2}))?\](.*)');
      final match = timeRegex.firstMatch(line);

      if (match != null) {
        final minutes = int.parse(match.group(1)!);
        final seconds = int.parse(match.group(2)!);
        final milliseconds = match.group(3) != null 
            ? int.parse(match.group(3)!) * 10 
            : 0;
        final text = match.group(4)?.trim() ?? '';

        final time = Duration(
          minutes: minutes,
          seconds: seconds,
          milliseconds: milliseconds,
        );
        lyrics.add(LyricLine(time: time, text: text));
      }
    }

    // 按时间排序
    lyrics.sort((a, b) => a.time.compareTo(b.time));
    return lyrics;
  }

  static int getCurrentLyricIndex(List<LyricLine> lyrics, Duration currentTime) {
    if (lyrics.isEmpty) return -1;

    for (int i = lyrics.length - 1; i >= 0; i--) {
      if (currentTime >= lyrics[i].time) {
        return i;
      }
    }
    return -1;
  }
}